#!/bin/sh
#
# SrvrPowerCtrl plugin helper script for linux.
#
# This script will set the system's RTC to wake the system up in advance of a programmed SqueezeCenter alarm.
#
# It attempts to accommodate hardware clocks set either to UTC or local time. (Thnx to rickwookie.)
#
#
# Copy this script to /usr/local/sbin/scwakeup_alt.sh: cp ./scwakeup_alt.sh /usr/local/sbin/scwakeup.sh
#
# Give root only permissions: chown root:root /usr/local/sbin/scwakeup.sh
#
# Make it executable: chmod a+x /usr/local/sbin/scwakeup.sh
#
# Test it:  sudo /usr/local/sbin/scwakeup.sh 1234567890
#
# View the log: cat /var/log/squeezecenter/srvrpowerctrl.log
#
# See http://www.mythtv.org/wiki/index.php/ACPI_Wakeup
# for apci wakeup troubleshooting...
#

function IsHWClockLocal ()
{
	RTCisLocal=0
	#Try to figure out if RTC is set to UTC or local time..
	rtcStatus=`/sbin/hwclock --debug --directisa`
	if [[ "$rtcStatus" =~ "Hardware clock is on UTC time" ]]; then
		RTCisLocal=0
	else
		RTCisLocal=1
	fi
	echo "$RTCisLocal"
}

function GetTZOffset ()
{
	localOffsetStr=`/bin/date +%z`

	if [[ $localOffsetStr =~ '\+' ]]; then
		IsWest=0
	else
		IsWest=1
	fi

	localOffsetHours="${localOffsetStr:1:2}"
	localOffsetHours=$((10#$localOffsetHours*3600))
	localOffsetMinutes="${localOffsetStr:3:2}"
	localOffsetMinutes=$((10#$localOffsetMinutes*60))
	localOffsetSeconds=$((10#$localOffsetHours+10#$localOffsetMinutes))

	if [[ $IsWest>0 ]]; then
		localOffsetSeconds=-$localOffsetSeconds
	fi

	echo "$localOffsetSeconds"
}

#Get the wakeup time from the cmd line arg..
wakeuptime=$1

log_file=/var/log/SBSVERSION/srvrpowerctrl.log
now_time=`/bin/date`
/bin/echo "$now_time: $0 $1" >> $log_file

HWClockIsLocal=`IsHWClockLocal`
wakeuptimeFixup=`GetTZOffset`

#this works for Fedora: if [[ $HWClockIsLocal -eq 1 ]]
if [[ $HWClockIsLocal -eq 1 ]]; then
	echo "HW Clock is set to local time.." >> $log_file
	wakeuptime=$(($wakeuptime+$wakeuptimeFixup))
else
	echo "HW Clock is set to UTC time.." >> $log_file
fi

wakeuptimep=`/bin/date -u -d "1970-01-01 $wakeuptime seconds" +"%Y-%m-%d %H:%M:%S"`

#Which type of RTC interface is present?

if [ -f /sys/class/rtc/rtc0/wakealarm ]; then
	#Kernels > 2.6.22 and higher use /sys/class/rtc/rtc0/wakealarm
	/bin/echo "Setting /sys/class/rtc/rtc0/wakealarm to $wakeuptime ($wakeuptimep)" >>$log_file
	/bin/echo 0 >/sys/class/rtc/rtc0/wakealarm
	/bin/echo $1 >/sys/class/rtc/rtc0/wakealarm

elif [ -f /proc/acpi/alarm ]; then
	#Kernels < 2.6.21 and lower use /proc/acpi/alarm
	#echo yyyy-mm-dd hh:mm:ss > /proc/acpi/alarm
	/bin/echo "Setting /proc/acpi/alarm to $wakeuptimep" >>$log_file
	/bin/echo $wakeuptimep >/proc/acpi/alarm
else
	/bin/echo "SrvrPowerCtrl does not support RTC wakeup on this system!" >>$log_file
fi


